package cn.holy.app.xcddt.ui.activity.base

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog

/**
 * Created by xionghao on 2018/2/22.
 */

abstract class BaseActivity : AppCompatActivity() {


    private val handler = Handler();
    private val dialogs = ArrayList<Dialog>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initLayout()
        initView()
        initData()
    }

    protected abstract fun initData()

    protected abstract fun initView()

    protected abstract fun initLayout()


    protected fun getLoading(loading: String): QMUITipDialog {
        val loading = QMUITipDialog.Builder(this).setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord(loading)
                .create()
        dialogs.add(loading);
        return loading;
    }

    protected fun hideLoading(loading: Dialog){
        hideDialog(loading);
    }

    protected fun showTips(tipWord: String, iconType: Int) {
        val tipDialog = QMUITipDialog.Builder(this).setIconType(iconType)
                .setTipWord(tipWord)
                .create()
        tipDialog.show()
        dialogs.add(tipDialog);
        handler.postDelayed({
            hideDialog(tipDialog);
        }, 1500)
    }

    private fun hideDialogs() {
        if (dialogs.size > 0) {
            dialogs.forEach {
                if (it.isShowing) {
                    it.dismiss();
                }
            }
            dialogs.clear();
        }

    }

    private fun hideDialog(dialog: Dialog) {
        if (dialogs.contains(dialog)) {
            dialogs.remove(dialog);
        }
        if (dialog.isShowing) {
            dialog.dismiss();
        }
    }

    protected fun showToast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        hideDialogs();
    }


    protected fun showTips(tipWord: String, iconType: Int, callback: Callback) {
        val tipDialog = QMUITipDialog.Builder(this).setIconType(iconType)
                .setTipWord(tipWord)
                .create()
        tipDialog.show()
        dialogs.add(tipDialog);
        handler.postDelayed({
            hideDialog(tipDialog);
            callback.onSuccess()
        }, 1500)
    }

    interface Callback {
        fun onSuccess()
    }


}
